package com.ruoyi.cderp.service.impl;

import java.util.List;

import com.ruoyi.cderp.domain.*;
import com.ruoyi.cderp.mapper.*;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.cderp.service.ITblPurchaseReturnService;

/**
 * 采购退单Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-06
 */
@Service
public class TblPurchaseReturnServiceImpl implements ITblPurchaseReturnService
{
    // 存储当前登录用户对象
    LoginUser loginUser = null;
    @Autowired
    private TblPurchaseReturnMapper tblPurchaseReturnMapper;
    @Autowired
    private TblPurchaseOrderMapper tblPurchaseOrderMapper;
    @Autowired
    private TblReceiveSheetMapper tblReceiveSheetMapper;
    @Autowired
    private ProductInfoMapper productInfoMapper;
    @Autowired
    private TblProductStockMapper tblProductStockMapper;
    @Autowired
    private MaterialMapper materialMapper;
    @Autowired
    private MaterialStockMapper materialStockMapper;

    /**
     * 查询采购退单
     *
     * @param id 采购退单主键
     * @return 采购退单
     */
    @Override
    public TblPurchaseReturn selectTblPurchaseReturnById(String id)
    {
        TblPurchaseReturn tblPurchaseReturn=tblPurchaseReturnMapper.selectTblPurchaseReturnById(id);

        //判断类型是否为物料
        for (TblPurchaseReturnDetail detail:tblPurchaseReturn.getTblPurchaseReturnDetailList()){
            int num=detail.getPurchaseType();
            if (num==1){
                Material material=materialMapper.selectMaterialById(detail.getMaterialId());
                detail.setMaterial(material);
            }
        }

        //查找关联的采购订单
        TblPurchaseOrder tblPurchaseOrder=tblPurchaseOrderMapper.selectTblPurchaseOrderById(tblPurchaseReturn.getPurchaseOrderId());
        tblPurchaseReturn.setTblPurchaseOrder(tblPurchaseOrder);

        //查找关联采购订单明细
        for (TblPurchaseReturnDetail tblPurchaseReturnDetail:tblPurchaseReturn.getTblPurchaseReturnDetailList()) {
            for (TblPurchaseOrderDetail detail:tblPurchaseOrder.getTblPurchaseOrderDetailList()){
                if (detail.getId().equals(tblPurchaseReturnDetail.getPurchaseOrderDetailId())){
                    tblPurchaseReturnDetail.setTblPurchaseOrderDetail(detail);
                }
            }
            tblPurchaseReturnDetail.setProductInfo(productInfoMapper.selectProductInfoById(tblPurchaseReturnDetail.getProductId()));
        }
        return tblPurchaseReturn;
    }

    /**
     * 查询采购退单列表
     *
     * @param tblPurchaseReturn 采购退单
     * @return 采购退单
     */
    @Override
    public List<TblPurchaseReturn> selectTblPurchaseReturnList(TblPurchaseReturn tblPurchaseReturn)
    {
        // 获取当前登录用户对象
        loginUser = SecurityUtils.getLoginUser();
        List<TblPurchaseReturn> list=tblPurchaseReturnMapper.selectTblPurchaseReturnList(tblPurchaseReturn);

        //判断是否为物料退货
        for (TblPurchaseReturn purchaseReturn:list){
            int num=purchaseReturn.getTblPurchaseReturnDetailList().get(0).getPurchaseType();
            if (num==1){
                for (TblPurchaseReturnDetail detail:purchaseReturn.getTblPurchaseReturnDetailList()){
                    Material material=materialMapper.selectMaterialById(detail.getMaterialId());
                    detail.setMaterial(material);
                }
            }
        }

        TblPurchaseOrder tblPurchaseOrder=null;

        //退货详情中的采购订单和商品赋值
        for (TblPurchaseReturn tblPurchaseReturn1:list) {
            tblPurchaseOrder=tblPurchaseOrderMapper.selectTblPurchaseOrderById(tblPurchaseReturn1.getPurchaseOrderId());
            tblPurchaseReturn1.setTblPurchaseOrder(tblPurchaseOrder);
            for (TblPurchaseReturnDetail tblPurchaseReturnDetail:tblPurchaseReturn1.getTblPurchaseReturnDetailList()) {
                for (TblPurchaseOrderDetail detail:tblPurchaseOrder.getTblPurchaseOrderDetailList()){
                    if (detail.getId().equals(tblPurchaseReturnDetail.getPurchaseOrderDetailId())){
                        tblPurchaseReturnDetail.setTblPurchaseOrderDetail(detail);
                    }
                }
                tblPurchaseReturnDetail.setProductInfo(productInfoMapper.selectProductInfoById(tblPurchaseReturnDetail.getProductId()));
            }
        }
        return list;
    }

    /**
     * 新增采购退单
     *
     * @param tblPurchaseReturn 采购退单
     * @return 结果
     */
    @Transactional
    @Override
    public int insertTblPurchaseReturn(TblPurchaseReturn tblPurchaseReturn)
    {
        //获取采购收货
        List<TblReceiveSheet> receiveSheetAllList=tblReceiveSheetMapper.selectTblReceiveSheetList(null);
        List<TblReceiveSheet> receiveSheetList=new ArrayList<>();

        for (TblReceiveSheet receiveSheet:receiveSheetAllList) {
            if (receiveSheet.getPurchaseOrderId().equals(tblPurchaseReturn.getPurchaseOrderId())){
                receiveSheetList.add(receiveSheet);
            }
        }

        //采购订单修改
        tblPurchaseOrderMapper.deleteTblPurchaseOrderDetailByOrderId(tblPurchaseReturn.getPurchaseOrderId());
        List<TblPurchaseOrderDetail> list=new ArrayList<>();
        for (TblPurchaseReturnDetail tblPurchaseReturnDetail: tblPurchaseReturn.getTblPurchaseReturnDetailList()){
            list.add(tblPurchaseReturnDetail.getTblPurchaseOrderDetail());

            //判断是否需要修改采购收货
            TblPurchaseOrderDetail detail=tblPurchaseReturnDetail.getTblPurchaseOrderDetail();
            long orderNum=detail.getOrderNum();         //采购订单数量
            long receiveNum=detail.getReceiveNum();     //采购收货数量
            long returnNum=detail.getReturnNum();       //采购退货数量
            if (returnNum>(orderNum-receiveNum)){
                //验证通过，获取还需退出的商品数量，并循环每一个相匹配的采购收货进行递减
                long num=returnNum-(orderNum-receiveNum);
                for (TblReceiveSheet receiveSheet:receiveSheetList) {
                    for (TblReceiveSheetDetail receiveSheetDetail:receiveSheet.getTblReceiveSheetDetailList()){
                        if (receiveSheetDetail.getPurchaseOrderDetailId().equals(detail.getId())){

                            //获取当前收货详情中还可退出的商品数量
                            long sum=receiveSheetDetail.getReceiveNum()-receiveSheetDetail.getReturnNum();

                            //判断当前收货详情中还可退出的商品数量是否大于需退出的商品数量
                            //如果大于则直接将收货详情中的退货数量加上需退出的商品数量
                            //相反则将收货详情中的可退数量拉满，并减去已退数量进入下一次循环继续执行递减操作
                            if (sum<num){
                                receiveSheetDetail.setReturnNum(receiveSheetDetail.getReturnNum()+sum);
                            }else {
                                receiveSheetDetail.setReturnNum(receiveSheetDetail.getReturnNum()+num);
                            }
                            num-=sum;

                            break;
                        }
                    }

                    //判断是否还需要执行递减操作
                    if(num<=0){
                        break;
                    }
                }
            }
        }
        tblPurchaseOrderMapper.batchTblPurchaseOrderDetail(list);

        //执行采购收货详情的数据修改
        List<TblReceiveSheetDetail> detailList=new ArrayList<>();
        for (TblReceiveSheet receiveSheet: receiveSheetList) {
            for (TblReceiveSheetDetail receiveSheetDetail: receiveSheet.getTblReceiveSheetDetailList()){
                detailList.add(receiveSheetDetail);
            }
            tblReceiveSheetMapper.deleteTblReceiveSheetDetailBySheetId(receiveSheet.getId());
        }
        if (detailList.size()>0){
            tblReceiveSheetMapper.batchTblReceiveSheetDetail(detailList);
        }


        //采购退单修改
        tblPurchaseReturn.setCreateTime(DateUtils.getNowDate());

        tblPurchaseReturn.setCreateById(loginUser.getUser().getUserId().toString());
        tblPurchaseReturn.setCreateBy(loginUser.getUser().getUserName());

        int rows = tblPurchaseReturnMapper.insertTblPurchaseReturn(tblPurchaseReturn);
        insertTblPurchaseReturnDetail(tblPurchaseReturn);
        return rows;
    }

    /**
     * 修改采购退单
     *
     * @param tblPurchaseReturn 采购退单
     * @return 结果
     */
    @Transactional
    @Override
    public int updateTblPurchaseReturn(TblPurchaseReturn tblPurchaseReturn)
    {
        //获取采购收货
        TblReceiveSheet tblReceiveSheet=new TblReceiveSheet();
        tblReceiveSheet.setPurchaseOrderId(tblPurchaseReturn.getPurchaseOrderId());
        List<TblReceiveSheet> receiveSheetList=tblReceiveSheetMapper.selectTblReceiveSheetList(tblReceiveSheet);

        //商品库存修改
        if (tblPurchaseReturn.getStatus()==3){
            for (TblPurchaseReturnDetail tblPurchaseReturnDetail : tblPurchaseReturn.getTblPurchaseReturnDetailList()) {
                if (tblPurchaseReturnDetail.getPurchaseType()==0){
                    TblProductStock tblProductStock=tblPurchaseReturnDetail.getProductInfo().getTblProductStock();
                    tblProductStockMapper.deleteTblProductStockById(tblProductStock.getId());
                    tblProductStockMapper.insertTblProductStock(tblProductStock);
                }else {
                    MaterialStock materialStock=tblPurchaseReturnDetail.getMaterial().getMaterialStock();
                    materialStockMapper.deleteMaterialStockById(materialStock.getId());
                    materialStockMapper.insertMaterialStock(materialStock);
                }
            }

            TblPurchaseReturn tblPurchaseReturn1=new TblPurchaseReturn();
            tblPurchaseReturn1.setPurchaseOrderId(tblPurchaseReturn.getPurchaseOrderId());
            List<TblPurchaseReturn> list=selectTblPurchaseReturnList(tblPurchaseReturn1);
            boolean info=true;

            for (TblPurchaseReturn str:list){
                if (!str.getId().equals(tblPurchaseReturn.getId())){
                    if (str.getStatus()!=3){
                        info=false;
                    }
                }
            }

            if (info){
                for (TblReceiveSheet receiveSheet:receiveSheetList){
                    boolean  info1=true;

                    for (TblReceiveSheetDetail receiveSheetDetail:receiveSheet.getTblReceiveSheetDetailList()){
                        if (receiveSheetDetail.getReturnNum()!=receiveSheetDetail.getReceiveNum()){
                            info1=false;
                            break;
                        }
                    }
                    if (info1){
                        TblReceiveSheet str=new TblReceiveSheet();
                        str.setId(receiveSheet.getId());
                        str.setStatus(Long.valueOf(6));
                        str.setRefuseReason("已退货");
                        tblReceiveSheetMapper.updateTblReceiveSheet(str);
                    }
                }
            }
        }else {
            //采购收货修改
            tblPurchaseOrderMapper.deleteTblPurchaseOrderDetailByOrderId(tblPurchaseReturn.getPurchaseOrderId());

            List<TblPurchaseOrderDetail> list=new ArrayList<>();
            for (TblPurchaseReturnDetail tblPurchaseReturnDetail: tblPurchaseReturn.getTblPurchaseReturnDetailList()){
                list.add(tblPurchaseReturnDetail.getTblPurchaseOrderDetail());

                //判断是否需要修改采购收货
                TblPurchaseOrderDetail detail=tblPurchaseReturnDetail.getTblPurchaseOrderDetail();
                long orderNum=detail.getOrderNum();         //采购订单数量
                long receiveNum=detail.getReceiveNum();     //采购收货数量
                long returnNum=detail.getReturnNum();       //采购退货数量
                if (returnNum>(orderNum-receiveNum)){
                    //验证通过，获取还需退出的商品数量，并循环每一个相匹配的采购收货进行递减
                    long num=returnNum-(orderNum-receiveNum);
                    for (TblReceiveSheet receiveSheet:receiveSheetList) {
                        for (TblReceiveSheetDetail receiveSheetDetail:receiveSheet.getTblReceiveSheetDetailList()){
                            if (receiveSheetDetail.getPurchaseOrderDetailId().equals(detail.getId())){

                                //判断是否还需要执行递减操作
                                if(num<=0){
                                    receiveSheetDetail.setReturnNum(Long.valueOf(0));
                                    break;
                                }

                                //获取当前收货详情中还可退出的商品数量
                                long sum=receiveSheetDetail.getReceiveNum();

                                //判断当前收货详情中还可退出的商品数量是否大于需退出的商品数量
                                //如果大于则直接将收货详情中的退货数量加上需退出的商品数量
                                //相反则将收货详情中的可退数量拉满，并减去已退数量进入下一次循环继续执行递减操作
                                if (sum<num){
                                    receiveSheetDetail.setReturnNum(sum);
                                }else {
                                    receiveSheetDetail.setReturnNum(num);
                                }
                                num-=sum;
                            }
                        }
                    }
                }
            }
            tblPurchaseOrderMapper.batchTblPurchaseOrderDetail(list);

            //执行采购收货详情的数据修改
            List<TblReceiveSheetDetail> detailList=new ArrayList<>();
            for (TblReceiveSheet receiveSheet: receiveSheetList) {
                for (TblReceiveSheetDetail receiveSheetDetail: receiveSheet.getTblReceiveSheetDetailList()){
                    detailList.add(receiveSheetDetail);
                }
                tblReceiveSheetMapper.deleteTblReceiveSheetDetailBySheetId(receiveSheet.getId());
            }
            if (detailList.size()>0){
                tblReceiveSheetMapper.batchTblReceiveSheetDetail(detailList);
            }
        }

        //采购退货修改
        tblPurchaseReturn.setUpdateTime(DateUtils.getNowDate());

        tblPurchaseReturn.setUpdateById(loginUser.getUser().getUserId().toString());
        tblPurchaseReturn.setUpdateBy(loginUser.getUser().getUserName());
        if (tblPurchaseReturn.getApproveBy()!=null){
            tblPurchaseReturn.setApproveBy((loginUser.getUser().getUserName()));
        }

        tblPurchaseReturnMapper.deleteTblPurchaseReturnDetailByReturnId(tblPurchaseReturn.getId());
        insertTblPurchaseReturnDetail(tblPurchaseReturn);
        return tblPurchaseReturnMapper.updateTblPurchaseReturn(tblPurchaseReturn);
    }

    /**
     * 批量删除采购退单
     *
     * @param ids 需要删除的采购退单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteTblPurchaseReturnByIds(String[] ids)
    {
        tblPurchaseReturnMapper.deleteTblPurchaseReturnDetailByReturnIds(ids);
        return tblPurchaseReturnMapper.deleteTblPurchaseReturnByIds(ids);
    }

    /**
     * 删除采购退单信息
     *
     * @param id 采购退单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteTblPurchaseReturnById(String id)
    {
        TblPurchaseReturn tblPurchaseReturn=selectTblPurchaseReturnById(id);

        //获取采购收货
        List<TblReceiveSheet> receiveSheetAllList=tblReceiveSheetMapper.selectTblReceiveSheetList(null);
        List<TblReceiveSheet> receiveSheetList=new ArrayList<>();

        for (TblReceiveSheet receiveSheet:receiveSheetAllList) {
            if (receiveSheet.getPurchaseOrderId().equals(tblPurchaseReturn.getPurchaseOrderId())){
                receiveSheetList.add(receiveSheet);
            }
        }

        //采购收货修改
        tblPurchaseOrderMapper.deleteTblPurchaseOrderDetailByOrderId(tblPurchaseReturn.getPurchaseOrderId());

        List<TblPurchaseOrderDetail> list=new ArrayList<>();
        for (TblPurchaseReturnDetail tblPurchaseReturnDetail: tblPurchaseReturn.getTblPurchaseReturnDetailList()){

            TblPurchaseOrderDetail detail=tblPurchaseReturnDetail.getTblPurchaseOrderDetail();
            long returnNum=tblPurchaseReturnDetail.getReturnNum();

            detail.setReturnNum(detail.getReturnNum()-returnNum);
            list.add(detail);

            for (TblReceiveSheet receiveSheet:receiveSheetList) {
                if (receiveSheet.getStatus()!=6){
                    for (TblReceiveSheetDetail receiveSheetDetail:receiveSheet.getTblReceiveSheetDetailList()){
                        if (receiveSheetDetail.getPurchaseOrderDetailId().equals(detail.getId())){
                            //获取当前收货单中的已退货数量
                            long receiveReturnNum=receiveSheetDetail.getReturnNum();

                            if (receiveReturnNum<returnNum){
                                receiveSheetDetail.setReturnNum(Long.valueOf(0));
                            }else {
                                receiveSheetDetail.setReturnNum(receiveReturnNum-returnNum);
                            }
                            returnNum-=receiveReturnNum;

                            break;
                        }
                    }
                }

                //判断是否还需要执行递减操作
                if(returnNum<=0){
                    break;
                }
            }
        }
        tblPurchaseOrderMapper.batchTblPurchaseOrderDetail(list);

        //执行采购收货详情的数据修改
        List<TblReceiveSheetDetail> detailList=new ArrayList<>();
        for (TblReceiveSheet receiveSheet: receiveSheetList) {
            for (TblReceiveSheetDetail receiveSheetDetail: receiveSheet.getTblReceiveSheetDetailList()){
                detailList.add(receiveSheetDetail);
            }
            tblReceiveSheetMapper.deleteTblReceiveSheetDetailBySheetId(receiveSheet.getId());
        }
        if (detailList.size()>0){
            tblReceiveSheetMapper.batchTblReceiveSheetDetail(detailList);
        }

        //采购退货删除
        tblPurchaseReturnMapper.deleteTblPurchaseReturnDetailByReturnId(id);
        return tblPurchaseReturnMapper.deleteTblPurchaseReturnById(id);
    }

    /**
     * 新增采购退单明细信息
     *
     * @param tblPurchaseReturn 采购退单对象
     */
    public void insertTblPurchaseReturnDetail(TblPurchaseReturn tblPurchaseReturn)
    {
        List<TblPurchaseReturnDetail> tblPurchaseReturnDetailList = tblPurchaseReturn.getTblPurchaseReturnDetailList();
        String id = tblPurchaseReturn.getId();
        if (StringUtils.isNotNull(tblPurchaseReturnDetailList))
        {
            List<TblPurchaseReturnDetail> list = new ArrayList<TblPurchaseReturnDetail>();
            for (TblPurchaseReturnDetail tblPurchaseReturnDetail : tblPurchaseReturnDetailList)
            {
                tblPurchaseReturnDetail.setReturnId(id);
                list.add(tblPurchaseReturnDetail);
            }
            if (list.size() > 0)
            {
                tblPurchaseReturnMapper.batchTblPurchaseReturnDetail(list);
            }
        }
    }
}
